package org.wpahs.ahn.rssfeed;


import android.util.Log;
import android.webkit.URLUtil;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


/**
 * Created by dgambone on 01/15/2015.
 */
public class FeedItem {


    private String title;
    private String link;
    private String description;
    private String pubDate;
    private int itemId = 0;
    private Boolean read = false;
    private int feedId;
    private String image;
    private Boolean hasImage = false;
    private String feedTitle = "";
    private Boolean isFavorite = false;
    private String ogImageUrl = null;

    private List<String> descriptionImages = new ArrayList<>();
    private List<String> mediaContentImages = new ArrayList<>();
    public List<String> mediaThumbImages = new ArrayList<>();

    DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
    DateFormat wsFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
    DateFormat wsFormatter1 = new SimpleDateFormat("MMM d',' yyyy");


    public FeedItem(int feedId) {
        setFeedId(feedId);
    }

    public FeedItem() {
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        //let's try to pull an image from the description
        if(description == null){
            description = "";
        }

        if (description.contains("<img")) {
            // pull image tags
            pullImageTags(description);
        }

        //description = Html.fromHtml(description).toString();
        //Log.i("Description after fromHtml",description);
        //description=description.replaceAll("<img.+/(img)*>", "");
        //Log.i("Description after img",description);

        this.description = description;
    }


    public String getPubDate() {
        return pubDate;
    }

    public Date getPubDateAsDate() {
        Date date = null;
        if (pubDate != null && !pubDate.equals("")) {
            date = new Date(Long.parseLong(pubDate));
        }
        return date;
    }

    public void setPubDateFromFeed(String pubDate) {
        if (pubDate != null && !pubDate.equals("")) {
            try {
                Date date = formatter.parse(pubDate);
                this.pubDate = String.valueOf(date.getTime());
            } catch (ParseException e) {
                // see if this one works
                try {
                    Date date = wsFormatter.parse(pubDate);
                    this.pubDate = String.valueOf(date.getTime());
                }catch (ParseException pe){
                    try {
                        Date date = wsFormatter1.parse(pubDate);
                        this.pubDate = String.valueOf(date.getTime());
                    }catch (ParseException pe1) {
                        Log.e("FeedItem", "Couldn't parse pub date - " + pubDate);
                    }
                }
            }
        } else {
            this.pubDate = pubDate;

        }
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }

    public int getItemId() {
        return itemId;
    }

    public void setItemId(int itemId) {
        this.itemId = itemId;
    }

    public void addDescriptionImage(String url) {
        if(URLUtil.isValidUrl(url)) {
            descriptionImages.add(url);
        }
    }

    public void addThumbnailImage(String url){
            mediaThumbImages.add(url);

    }

    public Boolean getRead() {
        return read;
    }

    public void setRead(Boolean read) {
        this.read = read;
    }

    public int getFeedId() {
        return feedId;
    }

    public void setFeedId(int feedId) {
        this.feedId = feedId;
    }

    private void pullImageTags(String html) {
        StringBuilder sb = new StringBuilder();
        sb.append("<root>"); sb.append(html);sb.append("</root>"); //add faux root
        DocumentBuilderFactory dBuilderFactory = DocumentBuilderFactory.newInstance();

        try {
            InputSource inputSource = new InputSource(new StringReader(sb.toString()));
            javax.xml.parsers.DocumentBuilder documentBuilder = dBuilderFactory.newDocumentBuilder();
            Document dom = documentBuilder.parse(inputSource);

            // get the root element.....
            Element docElement = dom.getDocumentElement();

            // now get the NodeList of root elements
            NodeList nodeList = docElement.getElementsByTagName("img");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                NamedNodeMap attributes = element.getAttributes();
                if(attributes != null){
                    Node src = attributes.getNamedItem("src");
                    Node border = attributes.getNamedItem("border"); //helps remove bad images feedburner images

                    if(src != null && border == null && !src.getNodeValue().toLowerCase().contains("feedburner")){
                        descriptionImages.add(src.getNodeValue());
                    }
                }
            }
        }
        catch (SAXException e) {
            //e.printStackTrace();
            tryParseOld(html);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    private void tryParseOld(String html) {
        //not good xml.  Do it the hard way.
        String imgStart = "<img";
        String imgEnd = ">";
        //find starts
        int startPos = 0;
        int endPos = 0;
        while (startPos != -1) {
            if ((startPos >= (html.length() - 1)) || (endPos >= html.length())) break;
            startPos = html.indexOf(imgStart, endPos);
            if (startPos == -1) break;
            //now find when this one ends
            endPos = html.indexOf(imgEnd, startPos + imgStart.length());
            if (endPos == -1) break;
            // let's find the src in between
            //grab the substring
            //Log.i("tryParse", String.valueOf(startPos) + " " + String.valueOf(endPos));
            String imgElement =
                    imgElement = html.substring(startPos, endPos);
            //now just the src
            String srcAttrib = "src=\"";
            int srcStart = imgElement.indexOf("src=\"");
            if (srcStart == -1) break;
            int srcEnd = imgElement.indexOf("\"", srcStart + srcAttrib.length());
            if (srcEnd == -1) break;
            String urlToImage = imgElement.substring(srcStart + srcAttrib.length(), srcEnd);
            if(URLUtil.isValidUrl(urlToImage)){
                descriptionImages.add(urlToImage);
            }
            //Log.i("tryParse-urlToImage",urlToImage);
        }
    }


    public String imageToDownload() {
        String retval = null;
        if(ogImageUrl != null){
            retval= ogImageUrl;
            Log.i("imageToDownload", "og:image-" + ogImageUrl);
        }
        if (retval == null && mediaThumbImages.size() > 0) {
            Log.i("imageToDownload", "mediaThumb-" + mediaThumbImages.get(0));
            retval = mediaThumbImages.get(0);
        }
        if(retval == null  && mediaContentImages.size() > 0){
            Log.i("imageToDownload", "mediaContent-" + mediaThumbImages.get(0));
            retval=  mediaContentImages.get(0);
        }

        if(retval == null && descriptionImages.size() > 0){
            retval= descriptionImages.get(0);
        }

        return retval;
    }


    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public Boolean getHasImage() {
        return hasImage;
    }

    public void setHasImage(Boolean hasImage) {
        this.hasImage = hasImage;
    }

    public String getFeedTitle() {
        return feedTitle;
    }

    public void setFeedTitle(String feedTitle) {
        this.feedTitle = feedTitle;
    }

    public Boolean getIsFavorite() {
        return isFavorite;
    }

    public void setIsFavorite(Boolean isFavorite) {
        this.isFavorite = isFavorite;
    }

    public String getOgImageUrl() {
        return ogImageUrl;
    }

    public void setOgImageUrl(String ogImageUrl) {
            this.ogImageUrl = ogImageUrl;

        // else it's null and leave it that way
    }
}
